const babylon = require('babylon')  //AST解析器
const babelparse = require('@babel/parser').parse;
const generate = require('@babel/generator').default
const traverse = require('@babel/traverse').default


class JsParser {
    /**
     * js转AST方法
     * @param text
     * @returns {Promise}
     */
    parse(text){
        return new Promise((resolve,reject)=>{
            try {
                const scriptParsed = babelparse(text,{
                    sourceType:'module',
                    plugins: [
                        "asyncGenerators",
                        "classProperties",
                        "decorators-legacy", //"decorators", 
                        "doExpressions",
                        "dynamicImport",
                        "exportExtensions",
                        "flow",
                        "functionBind",
                        "functionSent",
                        "jsx",
                        "objectRestSpread",
                    ]
                })
                resolve(scriptParsed)
            }catch (e){
                reject(e)
            }
        })
    }

    /**
     * 模板或AST对象转文本方法
     * @param astObject
     * @param code
     * @returns {*}
     */
    generate (astObject,code) {
        const newScript = generate(astObject, {}, code)
        return newScript
    }
}

module.exports = JsParser